package logic

import (
	"context"
	"encoding/json"
	"errors"
	"github.com/Baidu-AIP/golang-sdk/aip/censor"
	"log"
	"month/videosvr/common"
	"month/videosvr/internal/models"
	"month/videosvr/internal/service"

	"month/videosvr/internal/svc"
	"month/videosvr/video"

	"github.com/zeromicro/go-zero/core/logx"
)

type CommentLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCommentLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CommentLogic {
	return &CommentLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// Comment todo 评论回复
func (l *CommentLogic) Comment(in *video.CommentReq) (*video.CommentRes, error) {
	// todo: add your logic here and delete this line
	//todo  敏感词过滤
	client := censor.NewClient("i7GMCPKC5KW1oox4QGUWIWzd", "RYRWeQoUmfvsHQzWtBY2INqG2QUudtIz")
	censorRes := client.TextCensor(in.Comment)
	var censorMap map[string]interface{}
	json.Unmarshal([]byte(censorRes), &censorMap)
	if censorMap["conclusion"] == "不合规" {
		return &video.CommentRes{}, errors.New("消息不合规")
	}
	//todo rabbitmq异步存储
	//todo 生产者
	rabbitmq := common.NewRabbitMQSimple("" +
		"kuteng")
	rabbitmq.PublishSimple(in.Comment)
	//todo 消费者
	msgs, err := rabbitmq.ConsumeSimple()
	//todo 协程异步存储
	go func() {
		for d := range msgs {
			//消息逻辑处理，可以自行设计逻辑
			//todo 评论入库
			err = service.CreateComment(models.VideoComment{
				Userid:    int(in.Userid),
				Comment:   string(d.Body),
				LikeCount: 0,
				Pid:       int(in.CommentId),
			})
		}
	}()
	//todo 修改评论量
	//todo 查询数据库并+1
	videos, err := service.GetVideoInfo(int(in.CommentId))
	if err != nil {
		return &video.CommentRes{}, err
	}
	videos.CommentCount += 1
	log.Println(videos.CommentCount, "///////")
	//todo 保存修改后的数据
	err = service.SaveVideo(*videos)

	return &video.CommentRes{}, nil
}
